package com.cms.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;

import com.cms.entity.Order;
import com.cms.service.OrderService;
import com.cms.support.Result;

@Service
public class OrderServiceImpl extends BaseServiceImpl implements OrderService {

	public Result save(Order entity) {
		super.saveOrUpdate(entity);
		return new Result();
	}

	public Result updateStatus(Integer orderId, Integer status) {
		try {
			Order order = baseDao.get(Order.class, orderId);
			order.setStatus(status);
			baseDao.update(order);
			return new Result();
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, e.getMessage());
		}
	}

	public Result batchUpdate() {
		try {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
			baseDao.hqlUpdate(
					"update Order set status = 5 where goDate < ? and status=0",
					sf.format(new Date()));
			return new Result();
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, e.getMessage());
		}
	}

	@Override
	public List<Order> list(String userName, Integer pageSize, Integer pageNum) {
		batchUpdate();
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 20;
		}
		List<Order> orders = baseDao
				.sqlQuery(
						Order.class,
						"select * from T_CMS_ORDER where carId=? or custId=? order by createDate desc limit ?,?",
						userName, userName, (pageNum - 1) * pageSize, pageSize);
		return orders;
	}

	@Override
	public Boolean hasNoDoneOrder(String userName) {
		List<Order> orders = baseDao
				.sqlQuery(
						Order.class,
						"select * from T_CMS_ORDER where (carId=? or custId=?) and status = 0",
						userName, userName);
		if (orders != null && orders.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

}
